package me.zhenqu.web.controller;

import me.zhenqu.model.pojo.entity.Status;
import me.zhenqu.model.pojo.entity.User;
import me.zhenqu.services.StatusService;
import me.zhenqu.services.UserService;
import me.zhenqu.web.bvo.CountedStatus;
import me.zhenqu.web.bvo.SearchedUser;
import me.zhenqu.web.util.ContextParser;
import me.zhenqu.web.util.SessionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@Controller("privateController")
public class PrivateController {

    @Autowired
    private UserService userService;

    @Autowired
    private StatusService statusService;

    @RequestMapping(value = "/user/overview", method = GET)
    public String overview(final ModelMap modelMap, HttpSession session) {
        User user = SessionUtil.loadUser(session);
        if (user==null)
            return "signin";
        Long cuid = user.getUser_id();
        List<CountedStatus> countedStatusList = ObjectWraper.wrap(statusService.getUserTimeLines(cuid, 0), statusService);
        int following = userService.loadFollowingUserIds(cuid).size();
        int followed = userService.loadFollowedUserIds(cuid).size();
        int statuscount = statusService.getStatus(cuid,0).size();
        modelMap.addAttribute("following", following);
        modelMap.addAttribute("followed", followed);
        modelMap.addAttribute("countedStatusList", countedStatusList);
        modelMap.addAttribute("statuscount", statuscount);
        return "user/overview";
    }

    @RequestMapping(value = "/user/search", method = POST)
    public String search(@RequestParam(value = "keyword") final String keyword, final ModelMap modelMap, HttpSession session) {
        List<SearchedUser> searchedUserList = null;
        try {
            List<User> searchedUsers = userService.searchUserIds(keyword);
            User user = SessionUtil.loadUser(session);
            searchedUserList = ObjectWraper.wrapUser(user.getUser_id(), searchedUsers, userService);
        } catch (Exception e) {
            return "redirect:/404";
        }
        if (searchedUserList == null)
            return "redirect:/404";
        modelMap.addAttribute("keyword", keyword);
        modelMap.addAttribute("searchedUsers", searchedUserList);
        return "user/search_user_list";
    }

    @RequestMapping(value = "/user/publish", method = POST)
    public String publish(@RequestParam(value = "text") final String text, HttpSession session) {
        try {
            Status status = new Status();
            User user = SessionUtil.loadUser(session);
            status.setPubtime(new Date());
            status.setText(text);
            status.setUser_name(user.getNick_name());
            status.setUser_id(user.getUser_id());
            statusService.publish(status);
        } catch (Exception e) {
            return "redirect:/404";
        }
        return "redirect:/user/overview";
    }

    @RequestMapping(value = "/user/status_info/{status_id}", method = GET)
    public String status_info(@PathVariable("status_id") final String status_id, final ModelMap modelMap) {
        List<Status> comment_statuses = null;
        CountedStatus cs = null;
        try {
            Status current = statusService.getById(Long.parseLong(status_id));
            cs = ObjectWraper.wrap(current, statusService);
            comment_statuses = statusService.getComments(current);
        } catch (Exception e) {
            return "redirect:/404";
        }
        modelMap.put("currentStatus", cs);
        modelMap.put("comment_statuses",comment_statuses);
        return "user/status_info";
    }

    @RequestMapping(value = "/user/user_info/{user_id}", method = GET)
    public String user_info(@PathVariable("user_id") final String user_id, final ModelMap modelMap, HttpSession session) {
        User currentUser = null;
        List<CountedStatus>  countedStatusList = null;
        String followtype = null;
        boolean show = false;
        boolean needFollow = true;
        boolean cancelFollow = false;
        Long cuid = null;
        try {
            User user = SessionUtil.loadUser(session);
            cuid = Long.parseLong(user_id);
            if (user.getUser_id() != cuid) {
                boolean following = userService.isFollowing(user.getUser_id(), cuid);
                boolean followed = userService.isFollowed(user.getUser_id(), cuid);
                if (following)
                    needFollow = false;
                if (followed || following)
                    show = true;
                if (followed && following) {
                    followtype = "相互关注";
                    cancelFollow = true;
                }
                else if (followed)
                    followtype = "粉丝";
                else if (following){
                    followtype = "已关注";
                    cancelFollow = true;
                }
            } else
                needFollow = false;

            currentUser = userService.getById(cuid);
            countedStatusList = ObjectWraper.wrap(statusService.getStatus(cuid, 0), statusService);
            int statuscount = countedStatusList.size();
            int following = userService.loadFollowingUserIds(cuid).size();
            int followed = userService.loadFollowedUserIds(cuid).size();
            modelMap.addAttribute("following", following);
            modelMap.addAttribute("user", user);
            modelMap.addAttribute("followed", followed);
            modelMap.addAttribute("statuscount", statuscount);
        } catch (Exception e) {
            return "redirect:/404";
        }
        modelMap.addAttribute("show", show);
        modelMap.addAttribute("cancelFollow", cancelFollow);
        modelMap.addAttribute("needFollow", needFollow);
        modelMap.addAttribute("followtype", followtype);
        modelMap.addAttribute("currentUser", currentUser);
        modelMap.addAttribute("countedStatusList", countedStatusList);
        return "user/user_info";
    }

    @RequestMapping(value = "/user/follow/{user_id}", method = GET)
    public String follow(@PathVariable("user_id") final String user_id, HttpSession session) {
        try {
            User user = SessionUtil.loadUser(session);
            Long cuid = Long.parseLong(user_id);
            if (user.getUser_id() == cuid)
                return "user_info";
            else {
                userService.follow(user.getUser_id(), cuid);
            }
        } catch (Exception e) {
            return "redirect:/404";
        }
        return "redirect:/user/user_info/" + user_id;
    }

    @RequestMapping(value = "/user/{page}/retweet/{isComment}/{status_id}", method = GET)
    public String retweet(@PathVariable("page") final String page, @PathVariable("isComment") final String isComment,@PathVariable("status_id") final String status_id, @RequestParam(value = "text") String text, HttpSession session) {
        try {
            User user = SessionUtil.loadUser(session);
            Long statusuid = Long.parseLong(status_id);
            boolean comment = isComment.equals("0")?false:true;
            if (!comment){
                Status status = statusService.getById(statusuid);
                text += "//@"+status.getUser_name()+":"+status.getText();
            }
            statusService.retweet(user, statusuid, text,comment);
        } catch (Exception e) {
            return "redirect:/404";
        }
        String parsed = null;
        try{
            parsed = ContextParser.parse(page);
        }catch (RuntimeException e){
            return "redirect:/user/"+page;
        }
        return "redirect:/user/"+parsed;
    }

    @RequestMapping(value = "/user/{page}/delete/{status_id}", method = GET)
    public String delete(@PathVariable("page") final String page,@PathVariable("status_id") final String status_id, HttpSession session) {
        try {
            User user = SessionUtil.loadUser(session);
            Long statusIdLong = Long.parseLong(status_id);
            if (user.getUser_id()!= statusService.getById(statusIdLong).getUser_id())
                return "redirect:/error";
            statusService.delete(statusIdLong);
        } catch (Exception e) {
            return "redirect:/404";
        }
        String parsed = null;
        try{
            parsed = ContextParser.parse(page);
        }catch (RuntimeException e){
            return "redirect:/user/"+page;
        }
        return "redirect:/user/"+parsed;
    }

    @RequestMapping(value = "/user/cancelfollow/{user_id}", method = GET)
    public String cancelfollow(@PathVariable("user_id") final String user_id, HttpSession session) {
        try {
            User user = SessionUtil.loadUser(session);
            Long cuid = Long.parseLong(user_id);
            if (user.getUser_id() == cuid)
                return "user_info";
            else {
                userService.unfollow(user.getUser_id(), cuid);
            }
        } catch (Exception e) {
            return "redirect:/404";
        }
        return "redirect:/user/user_info/" + user_id;
    }

    @RequestMapping(value = "/user/user_list/{following}/{user_id}", method = GET)
    public String userlist(@PathVariable("following") final String following, @PathVariable("user_id") final String user_id, final ModelMap modelMap) {
        try {
            Long cuid = Long.parseLong(user_id);
            List<User> users = null;
            if (following.equals("1"))
                users = userService.loadFollowingUserIds(cuid);
            if (following.equals("0"))
                users = userService.loadFollowedUserIds(cuid);
            modelMap.put("users", users);
            modelMap.addAttribute("cuname", userService.getById(cuid).getNick_name());
            modelMap.put("following", following);
        } catch (Exception e) {
            return "redirect:/404";
        }
        return "user/user_list";
    }
}
